import { createRouter, createWebHistory } from 'vue-router';

const lazyLoad = (view) => () => import(`../view/${view}.vue`);

// 登录检查守卫
const requireAuth = (to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (isLoggedIn) {
    next(); // 已登录，允许进入页面
  } else {
    next({ name: 'Login' }); // 未登录，跳转到登录页面
  }
};

const routes = [
  {
    path: '/',
    name: 'Home',
    component: lazyLoad('IndexPage')
  },
  {
    path: '/index',
    name: 'Index',
    component: lazyLoad('IndexPage')
  },
  {
    path: '/login',
    name: 'Login',
    component: lazyLoad('LoginPage')
  },
  {
    path: '/register',
    name: 'Register',
    component: lazyLoad('RegisterPage')
  },
  {
    path: '/myPage',
    name: 'MyPage',
    component: lazyLoad('MyPage'),
    meta: { requiresAuth: true },
    beforeEnter: requireAuth // 复用登录检查逻辑
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: lazyLoad('OrderList'),
    meta: { requiresAuth: true },
    beforeEnter: requireAuth // 复用登录检查逻辑
  },{
    path: '/ordersPage',
    name: 'OrdersPage',
    component: lazyLoad('OrdersPage'),
  },
  {
    path: '/addUsersAddress',
    name: 'AddUsersAddress',
    component: lazyLoad('AddUsersAddress')
  },
  {
    path: '/editUserAddress',
    name: 'EditUserAddress',
    component: lazyLoad('EditUserAddress')
  },
  {
    path: '/userAddress',
    name: 'UserAddress',
    component: lazyLoad('UserAddress')
  },
  {
    path: '/paymentPage',
    name: 'PaymentPage',
    component: lazyLoad('PaymentPage')
  },
  {
    path: '/person',
    name: 'Person',
    component: lazyLoad('Person')
  },
  {
    path: '/changeName',
    name: 'ChangeName',
    component: lazyLoad('ChangeName')
  },
  {
    path: '/changePassword',
    name: 'ChangePassword',
    component: lazyLoad('ChangePassword')
  },
  {
    path: '/changeSex',
    name: 'ChangeSex',
    component: lazyLoad('ChangeSex')
  },
  {
    path: '/businessInfo',
    name: 'BusinessInfo',
    component: lazyLoad('BusinessInfo')
  },
  {
    path: '/changeImg',
    name: 'ChangeImg',
    component: lazyLoad('ChangeImg')
  },
  {
    path: '/businessList',
    name: 'BusinessList',
    component: lazyLoad('BusinessList')
  }
  // 其他路由
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

// 全局守卫进行登录检查
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录的页面
    if (!isLoggedIn) {
      next({ name: 'Login' }); // 未登录，跳转到登录页面
    } else {
      next(); // 已登录，继续访问
    }
  } else {
    // 不需要认证的页面
    next();
  }
});


export default router;
